package com.main.locatme;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.locatme.model.Enseigne;
import com.locatme.model.Personne;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.UtilisateurBD;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends Activity {

    private UtilisateurBD userBD;
    private Utilisateur user;
    private String login;
    private String password;
    private int type;

    private ProgressDialog pDialog;
    private JSONParser jsonParser = new JSONParser();

    private static final String urlConnect = "http://locatme.alwaysdata.net/locateme/connexion_utilisateur.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_LOGIN = "login";


    private RadioButton rd1 ;
    private RadioButton rd2 ;

    private EditText loginEditText;
    private EditText passEditText;

    public UtilisateurBD getUserBD() {
        return userBD;
    }

    public void setUserBD(UtilisateurBD userBD) {
        this.userBD = userBD;
    }

    public Utilisateur getUser() {
        return user;
    }

    public void setUser(Utilisateur user) {
        this.user = user;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            if(extras.getString("compte_cree").equals("oui")){
                Toast.makeText(LoginActivity.this, "Account created, you can log in", Toast.LENGTH_LONG).show();
            }
        }
        setContentView(R.layout.activity_login);
        final Button createButton = (Button) findViewById(R.id.create_account);
        final Button createProButton= (Button) findViewById(R.id.create_account_p);
        final Button loginButton = (Button) findViewById(R.id.connect);
        loginEditText = (EditText) findViewById(R.id.user_email);
        passEditText = (EditText) findViewById(R.id.user_password);
        rd1 = (RadioButton) findViewById(R.id.personne);
        rd2 = (RadioButton) findViewById(R.id.enseigne);

        rd1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                rd2.setChecked(false);
                type = 1;
            }
        });

        rd2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                rd1.setChecked(false);
                type = 2;

            }
        });

        //Creation de compte
        createButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent;
                intent = new Intent(LoginActivity.this, CreateActivity.class);
                startActivity(intent);
            }

        });

        createProButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent;
                intent = new Intent(LoginActivity.this, CreateEnseigneActivity.class);
                startActivity(intent);
            }

        });

        //Authentification
        loginButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (loginEditText.getText().toString().isEmpty() || passEditText.getText().toString().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "Please fill all required fields", Toast.LENGTH_LONG).show();
                } else {

                    if (isNetworkConnected(getApplicationContext())) {// faire le test de la connexion si oui---
                        try
                            {
                                new LoginUser().execute();
                            }
                        catch (Exception e)
                            {
                                Toast.makeText(LoginActivity.this,"Erreur de connexion, veuillez reessayer",Toast.LENGTH_LONG).show();
                            }
                    }
                    else
                    {
                        Toast.makeText(LoginActivity.this, "Pas de connexion Internet...", Toast.LENGTH_LONG).show();
                    }
                }
            }

        });
    }//Fin on create

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
    }

    public String getType()
    {
        String t= null;
        if(rd1.isChecked())
        {
            type=1;
            t = "Personne";
        }

        if(rd2.isChecked())
        {
            type=2;
            t = "Enseigne";
        }

        return t;
    }

    public boolean valider(View v) {
        boolean etat;
        userBD = new UtilisateurBD(this);

        switch (type) {
            case 1:
                user = new Personne();
                userBD.open();
                user = userBD.verifPersonne(login,password);
                break;

            case 2:
                user = new Enseigne();
                userBD.open();
                user = userBD.VerifEnseigne(login,password);
                break;
        }
        if (user!=null) {
            etat = true;
        } else {
            etat = false;
        }
        userBD.close();
        return etat;

    }


    class LoginUser extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(LoginActivity.this);
            pDialog.setMessage("Connexion ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {


            loginEditText = (EditText) findViewById(R.id.user_email);
            passEditText = (EditText) findViewById(R.id.user_password);

            login = loginEditText.getText().toString();
            password = passEditText.getText().toString();
            String typeUser =  getType();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_LOGIN, login));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("type", typeUser));
            JSONObject json = jsonParser.makeHttpRequest(urlConnect,
                    "POST", params);


            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    if(type==1){

                        user = new Personne();
                        user.setLogin(json.getString("login"));
                        user.setPwd(json.getString("password"));
                        intent.putExtra("user", (Personne) user);
                    }
                    else{
                        user = new Enseigne();
                        user.setLogin(json.getString("login"));
                        user.setPwd(json.getString("password"));
                        intent.putExtra("user",(Enseigne) user);
                    }
                    startActivity(intent);
                } else {
                    runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(LoginActivity.this," Login ou mot de passe erroné ",Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (JSONException e) {

                Log.d("Exeception de json : ", e.toString());
            }
            return null;

        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
        }
    }

}
